package main;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 
 * @author Brad
 */

public class MyConnection {
	private static Connection conn = null;

	/**
	 * Returns a connection object that is connected to the database. Use this
	 * connection object to make prepared statements based on SQL queries.
	 * 
	 * @return Will return a connection object if it connect to the database, otherwise
	 * 			returns  <b>null</b>
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		if (conn == null || conn.isClosed()) {
			Properties prop = new Properties();
			InputStream is;
			try {
				is = new FileInputStream("properties//connection.properties");  
				prop.load(is);  //

				Class.forName("com.mysql.jdbc.Driver"); // register the driver
				String dbURL = "jdbc:mysql://cs346.cs.uwosh.edu:4381/"
						+ prop.getProperty("db");
				System.out.println("Attempting connection");
				conn = DriverManager.getConnection(dbURL,
						prop.getProperty("db"), prop.getProperty("pw"));
				conn.setAutoCommit(true);
				System.out.println("Connection successful");
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				System.out.println("Error: " + e);
			}
			return conn;
		} else {
			return conn;
		}
	}

	/**
	 * Attempts to close the connection. If connection is already close the
	 * return type will still be true.
	 * 
	 * @return boolean whether or not connection was closed.
	 */
	public static boolean closeConnection() {
		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}
